// tradeDetail.js
const app = getApp()
import { requestApi } from '../../../api'
import { formatImage } from '../../../utils/formatImage'
import { formatTime, formatTimeHMS, formatPrice } from '../../../utils/util'


Page({

    /**
     * 页面的初始数据
     */
    data: {
        winWidth: 0,
        winHeight: 0,
        channel: '',
        loading: false,
        loadingText: '',
        checkItem: [{
            value: true,
            checked: true,
        }],
        trade_no: '',
        data: {},  // 订单详情数据
        timeArr: [],  // 订单时间线  
        remain_tip: '',
        activeStatus: '',
        is_reservation_trade: 0,
        shield_seller_info: '',
        tip: '',
        paySign: ''
    },
    //  取消订单
    cancelOrder: function () {
        let tip = this.data.tip || '您确认取消订单吗?(┬＿┬)'
        let data = {
            trade_no: this.data.trade_no,
            trade_status: this.data.data.trade_status,
            seller_uid: this.data.data.seller_uid,
            buyer_uid: this.data.data.buyer_uid,
            gid: this.data.data.gid,
            channel: this.data.channel,
            trade_cancel_code: 1,
        }
        let options = {
            url: requestApi.orderCancelUrl,
            data: data,
            method: 'POST'
        }

        this.confirmOperate(tip, options)
    },

    // productInfoTap: function () {
    //   console.log(this.data)
    //   wx.navigateTo({
    //     url: '../../goods/goodsDetail/goodsDetail?gid=' + this.data.data.gid + '&channel=' + this.data.channel + '&activeStatus=' + this.data.activeStatus,
    //   })
    // },

    // 去付款 
    payOrder: function () {
        if (this.data.data.upgrade_trigger == 1) {
            this.doneDialog.showDialog()

            return
        }

        if (!this.data.checkItem[0].checked) { // 没有勾选购买须知
            this.dialog.showDialog()

            return false
        }

        if (this.payStatus) return false

        this.payStatus = true

        // 进行付款操作，付款成功后跳转至订单详情页
        this.weixinPay(this.data.trade_no, () => {
            this.onLoad({
                trade_no: this.data.trade_no
            })
        })
    },
    // 提醒发货
    remindDelivery: function () {
        let tip = this.data.tip || '您确认提醒发货吗◔ ‸◔?'
        let data = {
            trade_no: this.data.trade_no,
            seller_uid: this.data.data.seller_uid,
            channel: this.data.channel
        }
        let options = {
            url: requestApi.remindDeliveryUrl,
            data: data,
            method: 'POST'
        }

        this.confirmOperate(tip, options)
    },
    // 确认收货
    confirmSign: function () {
        let tip = this.data.tip || '已验收商品，确定收货！记得拍个美照来评价晒单哦~❤'
        let tradeStatus = 5   // 点击确认收货后跳到订单列表待评价tab下
        let data = {
            trade_no: this.data.trade_no,
            channel: this.data.channel,
        }
        let options = {
            url: requestApi.confirmSignUrl,
            data: data,
            method: 'POST'
        }

        this.confirmOperate(tip, options, tradeStatus)
    },
    // 查询物流
    checkLogistics: function () {
        let trade_no = this.data.trade_no
        wx.navigateTo({
            url: '../logisticsInfo/logisticsInfo?trade_no=' + trade_no + '&channel=' + this.data.channel,
        })

    },
    // 立即评价
    evaluate: function () {
        let trade_no = this.data.trade_no
        wx.navigateTo({
            url: '../valuation/valuation?trade_no=' + trade_no + '&channel=' + this.data.channel,
        })
    },

    // 阅读购买须知选中
    purchaseNotesCheck: function (e) {
        let checked = e.detail.value[0] ? true : false

        this.setData({
            checkItem: [{
                value: true,
                checked: checked,
            }]
        })
    },

    // 跳转阅读须知页面
    readPurchaseNotes(e) {
        let protocolName = e.currentTarget.dataset.protocol
        let url = `../../goods/purchaseNotes/purchaseNotes?protocol_name=${protocolName}`

        wx.navigateTo({
            url: url,
        })
    },

    _cancelEvent() {
        this.dialog.hideDialog();
    },

    _confirmEvent() {
        this.setData({
            checkItem: [{
                value: true,
                checked: true,
            }]
        })

        this.payOrder()
        this.dialog.hideDialog();
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function (options) {
        let channel = options.channel || 'wx_xcx'

        this.data.channel = channel
        this.data.activeStatus = options.activeStatus

        this.defaultLoadingText = '加载中...'
        this.payStatus = false;

        if (options.trade_no) {
            this.data.trade_no = options.trade_no
        }

        let systemInfo = {}

        try {
            systemInfo = wx.getSystemInfoSync()
        } catch (e) {
            // Do something when catch error
        }

        this.setData({
            winWidth: systemInfo.windowWidth,
            winHeight: systemInfo.windowHeight,
        })

        this.doneDialog = this.selectComponent('#doneDialog')
    },

    onReady() {
        this.dialog = this.selectComponent("#authorizeDialog");
    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow: function () {
        if (app.toLogin()) {
            // 获取当前登陆的uid和openid
            wx.getStorage({
                key: 'userinfo',
                success: (res) => {
                    this.data.openid = res.data.openid
                }
            })

            this.getDetailData(this.data.trade_no, this.data.channel)
        }
        this.resetLoadingSettings()
    },

    // 恢复loading初始状态
    resetLoadingSettings: function () {
        this.setData({
            loading: true,
        })
        this.data.loadingText = this.defaultLoadingText
    },

    _confirmKnow() {
        this.doneDialog.hideDialog()
    },

    // 获取订单详情
    getDetailData: function (trade_no, channel) {
        let options = {
            url: requestApi.orderDetailUrl,
            data: {
                trade_no: trade_no,
                channel: channel,
            }

        }
        // 调用网络请求
        app.request(options,
            (result) => {
                var res = this.getDetailInfo(result)

                this.setData({
                    is_reservation_trade: result.original.is_reservation_trade,
                    data: res.original.trade_detail,
                    shield_seller_info: res.original.shield_seller_info,
                    timeArr: res.original.time_line,
                    tip: res.original.trade_detail.prompt_message
                })

                if (res.original.trade_detail.trade_status == 2) {
                    setInterval(this.getRemainTime, 1000)
                }
            }, function (error) {
                wx.showModal({
                    title: '提示',
                    content: error,
                    showCancel: false
                })
            }
        )
    },

    // 二次确认操作
    confirmOperate: function (tip, options, status) {
        // 点击确认收货后返回订单列表的待评价tab下，其他默认返回全部tab下
        let tradeStatus = arguments[2] ? arguments[2] : 0
        wx.showModal({
            title: '提示',
            content: tip,
            success: (res) => {
                if (res.confirm) {
                    app.request(
                        options,
                        (data) => {
                            wx.showToast({
                                title: data.original.msg,
                                duration: 1000
                            })
                            setTimeout(function () {
                                wx.navigateTo({
                                    url: '../../trade/tradeList/tradeList?tradeStatus=' + tradeStatus,
                                })
                            }, 1000)
                        },
                        (error) => {
                            wx.showModal({
                                title: '提示',
                                content: error,
                                showCancel: false
                            })
                        }
                    )
                }
            }
        })

    },

    // 倒计时功能
    getRemainTime: function () {
        if (!this.data.timeArr.length) {
            return
        }

        // 下单时间
        let orderTime = ''
        let payHour = ''
        if (this.data.data.trade_status == 1) { // 代购
            if (this.data.is_reservation_trade == 1) {
                orderTime = this.data.data.trigger_time
            } else {
                orderTime = this.data.timeArr[1].time
            }
            payHour = 24
        } else {  // 现货
            if (this.data.is_reservation_trade == 1) {
                orderTime = this.data.data.trigger_time
            } else {
                orderTime = this.data.timeArr[0].time
            }

            payHour = 2

            if (this.data.data.intimate_purchase_info) {
                payHour = 0.25
            }
        }

        let orderTimestamp = this.getDateTime(orderTime)
        let currentTimestamp = Date.now()
        let differTimestamp = (currentTimestamp - orderTimestamp) / 1000  // s为单位

        // 支付时间的timestamp
        let totalTimestamp = payHour * 60 * 60
        let remainTimestamp
        if (this.data.is_reservation_trade == 1) {
            remainTimestamp = 0 - differTimestamp
        } else {
            remainTimestamp = totalTimestamp - differTimestamp
        }

        if (remainTimestamp < 0) return

        let hour = parseInt(remainTimestamp / 3600)
        let minute = parseInt((remainTimestamp % 3600) / 60)

        this.setData({
            remain_tip: hour + '小时' + minute + '分钟后未付款,订单自动取消'
        })
    },

    getDateTime(datestring) {
        let result = datestring.match(/(\d+)\-(\d+)\-(\d+)\s+(\d+):(\d+):(\d+)/)
        let date = new Date()

        date.setFullYear(result[1])
        date.setMonth(result[2] - 1)
        date.setDate(result[3])

        date.setHours(result[4])
        date.setMinutes(result[5])
        date.setSeconds(result[6])

        return date.getTime()
    },

    weixinPay(tradeNo, successCallback) { // TODO 确认订单页、订单详情页，这两个页面的支付逻辑统一处理
        let params = {
            trade_no: tradeNo,
            channel: this.data.channel,
        }

        this.setData({
            loading: false,
            loadingText: '正在支付中...'
        })

        app.request({
            url: requestApi.weixinPayUrlAgent,
            method: 'POST',
            data: params,
        }, (data) => {
            this.setData({
                paySign: data.original.wechat_pay_detail
            })

            if (this.data.data.wechat_live_trace_id) {
                this.getRequireOrder(tradeNo, successCallback);
            } else {
                this.paymentHandler(tradeNo, 'requestPayment', successCallback);
            }
        }, (error) => {
            wx.showModal({
                title: '提示',
                showCancel: false,
                content: error,
            })
        }, () => {
            this.payStatus = false
            this.resetLoadingSettings()
        })
    },
    getDetailInfo(data) {
        if (data.original && data.original.trade_detail) {
            let trade_detail = data.original.trade_detail

            if (trade_detail.product_cover_image && trade_detail.product_cover_image.path) {
                trade_detail.product_cover_image.path_cn = formatImage.cdnImage(trade_detail.product_cover_image.path, formatImage.THUMBNAIL_M)
            }

            if (trade_detail.global_icon && trade_detail.global_icon.path) {
                trade_detail.global_icon.path_cn = formatImage.cdnImage(trade_detail.global_icon.path, formatImage.THUMBNAIL_M)
            }

            if (trade_detail.trade_status && ([1, 2, 4].includes(trade_detail.trade_status)) || trade_detail.trade_status == 5 && trade_detail.has_comment == 0 || trade_detail.trade_status == 3 && trade_detail.intimate_purchase_info && trade_detail.intimate_purchase_info.intimate_purchase_card && trade_detail.intimate_purchase_info.intimate_purchase_card.status != 2) {
                this.data.winHeight = this.data.winHeight - 50
            }

            trade_detail.trade_status_cn = this.getTradeStatusCn(trade_detail.trade_status, trade_detail.has_comment)
            // trade_detail.trade_tip = this.getTradeTip(trade_detail.trade_status)
            trade_detail.goods_spec_cn = trade_detail.goods_spec ? trade_detail.goods_spec.split('-')[0] : ''
            // trade_status == 3 && type==2 为亲密购订单 显示操作按钮
            trade_detail.operate_is_show = ([1, 2, 4, 5].includes(trade_detail.trade_status) || trade_detail.trade_status == 3 && (trade_detail.type != 2 || trade_detail.intimate_purchase_info && trade_detail.intimate_purchase_info.intimate_purchase_card && trade_detail.intimate_purchase_info.intimate_purchase_card.status != 2)) ? 1 : 0
            trade_detail.goods_price = trade_detail.goods_price ? '￥' + formatPrice(trade_detail.goods_price / 100) : '￥0'
            trade_detail.pay_price = trade_detail.pay_price ? '￥' + formatPrice(trade_detail.pay_price / 100) : '￥0'
            trade_detail.shipping_rate = trade_detail.shipping_rate ? '￥' + formatPrice(trade_detail.shipping_rate / 100) : '￥0'
            trade_detail.coupon_price = trade_detail.coupon_info && trade_detail.coupon_info.coupon_price ? '￥' + formatPrice(trade_detail.coupon_info.coupon_price / 100) : '￥0'
            trade_detail.seller_coupon_price = trade_detail.seller_coupon_price? '￥' + formatPrice(trade_detail.seller_coupon_price / 100) : '￥0'
            trade_detail.pay_customs_duties = trade_detail.pay_customs_duties ? '￥' + formatPrice(trade_detail.pay_customs_duties / 100) : '￥0'
            trade_detail.seller_avatar_img = formatImage.cdnImage(trade_detail.seller_avatar_img)

            // 运费
            trade_detail.shipping_rate_show = ''
            if (trade_detail.shipping_rate_pay_arrived == 1 && trade_detail.shipping_rate != 0) {
                trade_detail.shipping_rate_show = trade_detail.shipping_rate
            }
            if (trade_detail.shipping_rate_pay_arrived == 1 && trade_detail.shipping_rate == 0) {
                trade_detail.shipping_rate_show = '商家包邮'
            }
            if (trade_detail.shipping_rate_pay_arrived == 2) {
                trade_detail.shipping_rate_show = '到付'
            }
            // 税费
            trade_detail.customs_duties_show = ''
            if (trade_detail.customs_duties_type == 0) {
                trade_detail.customs_duties_show = trade_detail.customs_duties
            } else if (trade_detail.customs_duties_type == 1) {
                trade_detail.customs_duties_show = '商家包税'
            } else {
                trade_detail.customs_duties_show = '买家自理'
            }

            // 现货（国内现货1 国外现货2） 代购3  goods_channel_source_cn 1=> 代购 2=> 现货
            trade_detail.goods_channel_source_cn = trade_detail.goods_channel_source && trade_detail.goods_channel_source == 3 ? 1 : 2

            // 小拼团订单展示用户头像
            if (trade_detail.intimate_purchase_info && trade_detail.intimate_purchase_info.intimate_purchase_card && trade_detail.intimate_purchase_info.intimate_purchase_card.user_list.length) {
                for (let i = 0; i < trade_detail.intimate_purchase_info.intimate_purchase_card.user_list.length; i++) {
                    trade_detail.intimate_purchase_info.intimate_purchase_card.user_list[i]['path'] = formatImage.cdnImage(trade_detail.intimate_purchase_info.intimate_purchase_card.user_list[i]['path'])
                }
            }
            // 状态为拼团中，显示活动倒计时
            if (trade_detail.intimate_purchase_info && trade_detail.intimate_purchase_info.intimate_purchase_card && trade_detail.intimate_purchase_info.intimate_purchase_card.status == 2) {
                let remainTime = trade_detail.intimate_purchase_info.intimate_purchase_card.remain_time
                let interval = setInterval(() => {
                    let formatRemainTime = formatTimeHMS(remainTime)
                    remainTime = remainTime - 1
                    this.setData({
                        formatRemainTime: formatRemainTime,
                    })

                    if (remainTime < 0) {
                        clearInterval(interval)
                    }
                }, 1000)
            }

            data.original.trade_detail = trade_detail
        }

        return data
    },
    getTradeStatusCn(status, comment) {
        switch (status) {
            case -1:
                return '交易完成';
            case 1:
                return '等待商家接单';
            case 2:
                return '等待您付款';
            case 3:
                return '等待商家发货';
            case 4:
                return '等待您签收';
            case 5:
                return comment == 0 ? '等待您评价' : '评价完成';
            case 6:
                return '商家拒绝接单';
            case 7:
                return '商家待发货';
            case 8:
                return '退款成功';
            case 9:
                return '买家取消订单';
            case 10:
                return '订单已关闭';
            case 11:
                return '退款中';
        }
    },
    // getTradeTip(status) {
    //     switch (status) {
    //         case 1:
    //             return '代购商品,请等待商家接单后再付款';
    //         case 4:
    //             return '收到快递请拆开检查再签收';
    //         default:
    //             return '';
    //     }
    // },

    //店铺详情
    shopTap: function (e) {
        let seller_uid = e.currentTarget.dataset.id

        app.request({
            url: requestApi.isFlashStore,
            login: false,
            data: {
                seller_uid: seller_uid
            },
        }, (data) => {
            if (data.original.data.is_flash) {
                wx.navigateTo({
                    url: '/pages/shop/shop?shop_id=' + data.original.data.id + '&seller_uid=' + seller_uid,
                })
            } else {
                wx.navigateTo({
                    url: '../../store/store?seller_uid=' + seller_uid,
                })
            }
        }, (error) => {
            wx.showModal({
                title: '提示',
                showCancel: false,
                content: error,
            })
        })
    },

    // 获取视频号订单信息
    getRequireOrder(trade_no, successCallback) {
        const { channel  } = this.data;
        const self = this;
        
        wx.showLoading({
            title: '数据请求中',
        });
        app.request({
            url: requestApi.wxLivePayUrl,
            method: 'POST',
            data: {
                trade_no,
                is_new_ver: true,
                channel: channel
            },
        }, (data) => {
            self.setData({
                paySign: data.original.wechat_pay_detail
            })

            self.paymentHandler(trade_no, 'requestOrderPayment', successCallback);
        }, (error) => {
            // 
        }, () => {
            wx.hideLoading();
        })
    },

    paymentHandler(trade_no, paymentType, successCallback) {
        let signData = this.data.paySign || {};
        delete signData['status']
        delete signData['appId']

        // 微信支付成功回调
        signData.success = () => {
            // 回调通知接口
            app.request({
                url: requestApi.weixinPayCallback,
                method: 'POST',
                data: {
                    trade_no
                }
            }, (data) => {
                // successCallback && successCallback()
            }, (error) => {
                // wx.showModal({
                // 	title: '提示',
                // 	showCancel: false,
                // 	content: error.errMsg,
                // })
            }, () => {
                successCallback && successCallback()
            })
        }

        // 微信支付失败回调
        signData.fail = (error) => {
            if (error.errMsg == paymentType + ':fail cancel') { // 用户取消支付
            } else { // 调用支付失败 TODO 上报支付失败原因
                wx.showModal({
                    title: '提示',
                    showCancel: false,
                    content: error.errMsg == 'OK' ? '您已支付成功，请刷新页面' : error.errMsg,
                })
            }
        }

        wx[paymentType](signData);
    }
})